package cn.huijielong.modules.group.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.pagehelper.Page;

import cn.huijielong.common.utils.DateUtils;
import cn.huijielong.common.utils.PageUtils;
import cn.huijielong.common.utils.Query;
import cn.huijielong.common.utils.RD;
import cn.huijielong.common.utils.VSUtil;
import cn.huijielong.modules.group.entity.GoodsEntity;
import cn.huijielong.modules.group.entity.GroupEntity;
import cn.huijielong.modules.group.service.GoodsService;
import cn.huijielong.modules.group.service.GroupService;
import cn.huijielong.modules.pub.entity.LocationEntity;
import cn.huijielong.modules.pub.entity.MerchantEntity;
import cn.huijielong.modules.pub.service.LocationService;
import cn.huijielong.modules.solitaire.entity.SolitaireEntity;
import cn.huijielong.modules.solitaire.service.SolitaireService;
import cn.huijielong.modules.sys.controller.AbstractController;




/**
 * 团购
 * 
 * @author xys
 * @email xys@gmail.com
 * @date 2019-07-03 22:46:43
 */
@RestController
@RequestMapping("/group/group")
public class GroupController  extends AbstractController{
	@Autowired
	private GroupService groupService;
	@Autowired
	private SolitaireService solitaireService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private LocationService locationService;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	public RD list(@RequestParam Map<String, Object> params){
	    logger.info("从{}发送请求，参数：{}",getHeader("referer"),params.toString());
		//查询列表数据
        Query query = Query.createRequest(params);
        if(!query.containsKey("status")) {
        	query.addParam("status", "0");
        }
		Page<GroupEntity> groupList = groupService.queryList(query);		
		PageUtils pageUtil = new PageUtils(groupList, groupList.getTotal(), query.getLimit(), query.getPage());
		
		return RD.ok().put("page", pageUtil);
	}
	@RequestMapping("/queryCurGroupId/{curPage}")
	public RD queryCurGroupId(@PathVariable("curPage") Long curPage){
		//查询列表数据
		Query rq = groupService.queryCurGroupId(curPage);	
		return RD.ok().setData(rq);
	}
	
	
	/**
	 * 信息
	 */
	@RequestMapping("/info/{groupId}")
	public RD info(@PathVariable("groupId") Long groupId){
		GroupEntity group = groupService.queryObject(groupId);
		SolitaireEntity solitaire=solitaireService.queryObject(groupId);
		group.setSolitaire(solitaire);
		LocationEntity location=locationService.queryObject(group.getLocationId());
		if(location!=null) {
			group.setLocation(location);
		}
		return RD.ok().put("group", group);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("group:group:save")
	public RD save(){//@RequestBody 传入json时使用这个
		net.sf.json.JSONObject jsonGroup=VSUtil.requestToJSON();
		Long merId=MerchantEntity.getMerchantIdByRequest();
		Long userId=getUserId();
		if(merId==null || merId.longValue()==0) {
			logger.error("商户ID为0，该商户是测试商户，不能操作");
			return RD.error("没有操作权限");
		}
		if(userId==null || userId.longValue()==0) {
			logger.error("用户ID为0，未登录，不能操作");
			return RD.error("未登录，不能操作");
		}
		
		//接龙表数据
		SolitaireEntity solitaire=new SolitaireEntity();
		solitaire.setName(jsonGroup.optString("name"));
		solitaire.setMerchantId(merId);
		solitaire.setEndDate(DateUtils.parseDate(jsonGroup.optString("endDate")));
		solitaire.setSendDate(DateUtils.parseDate(jsonGroup.optString("sendDate")));
		solitaire.setDescription(jsonGroup.optString("description"));
		solitaire.setHeadImg(jsonGroup.optString("headImg"));
		solitaire.setType(SolitaireEntity.TYPE_GROUP);
		
		//团购数据
		GroupEntity group=new GroupEntity();
		if(jsonGroup.containsKey("solitaireId")) {
			group.setGroupId(jsonGroup.optLong("solitaireId"));
			solitaire.setSolitaireId(group.getGroupId());
		}
		group.setSolitaire(solitaire);
		group.setLocationId(jsonGroup.optLong("locationId"));
		
		//团购商品项数据
		List<GoodsEntity> goodsList=new ArrayList<>();
		net.sf.json.JSONArray jsonGoodsList=jsonGroup.optJSONArray("goodsList");
		for(int i=0;i<jsonGoodsList.size();i++) {
			net.sf.json.JSONObject jsonGoods=jsonGoodsList.getJSONObject(i);
			GoodsEntity goods=new GoodsEntity();
			goods.setName(jsonGoods.optString("name"));
			goods.setPrice(VSUtil.getDecimal(jsonGoods, "price"));
			goods.setUnit(jsonGoods.optString("unit"));
			goods.setTotalNum(jsonGoods.optInt("totalNum"));
			if(jsonGoods.containsKey("goodsId"))
				goods.setGoodsId(jsonGoods.optLong("goodsId"));
			goods.setHeadImg(jsonGoods.optString("headImg"));
			goodsList.add(goods);
		}
		group.setGoodsList(goodsList);
		if(group.getGroupId()==null)
			solitaireService.save(solitaire, p->{
				group.setGroupId(p.getSolitaireId());
				groupService.save(group);
			});
		else 
			solitaireService.update(solitaire, p->groupService.update(group));
		//返回数据
		RD rd=RD.ok();
		List<Query> list=new ArrayList<>();
		//返回团购图片。图片地址以“http://tmp/”开头的才能上传，这种图片是小程序本地选择的图片
		if(solitaire.getHeadImg()!=null && solitaire.getHeadImg().startsWith("http://tmp/")) {
			Query g=Query.empty();
			g.addParam("rowId", group.getGroupId());
			g.addParam("tableType", "group");
			g.addParam("headImg", solitaire.getHeadImg());
			list.add(g);
		}
		//返回商品图片。图片地址以“http://tmp/”开头的才能上传，这种图片是小程序本地选择的图片
		for(GoodsEntity goods:group.getGoodsList()) {
			if(goods.getHeadImg()!=null  && goods.getHeadImg().startsWith("http://tmp/")) {
				Query item=Query.empty();
				item.addParam("rowId", goods.getGoodsId());
				item.addParam("tableType", "goods");
				item.addParam("headImg", goods.getHeadImg());
				list.add(item);
			}
		}
		return rd.put("images", list);
	}
	@RequestMapping("/uploadImage")
	@RequiresPermissions("group:group:save")
	public RD uploadImage(HttpServletRequest request){
		MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        //对应前端的upload的name参数"file"
        MultipartFile multipartFile = req.getFile("headImg");
        if(multipartFile==null)
        {
        	logger.error("图片上传失败，文件不能为空");
        	return RD.error("图片文件不能为空");
        }
        String rowId=req.getParameter("rowId");
        String tableType=req.getParameter("tableType");
        String add=req.getParameter("add");
        if("group".equals(tableType)) {
        	solitaireService.uploadHeadImage(Arrays.asList(multipartFile), Long.parseLong(rowId), "Y".equals(add));
        }else {
        	goodsService.uploadImage(Arrays.asList(multipartFile), Long.parseLong(rowId), "Y".equals(add));
        }
		return RD.ok();
	}
	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("group:group:update")
	public RD update(@RequestBody GroupEntity group){
		groupService.update(group);
		
		return RD.ok();
	}
	
}
